package com.monitor.utils;

import com.monitor.config.zmq.JsonMsgOperType;
import com.monitor.config.zmq.JsonMsgRequestType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zeromq.SocketType;
import org.zeromq.ZMQ;

import java.nio.charset.StandardCharsets;

/**
 * TcpClient发送消息工具类
 *
 * @author Administrator
 */
public class ZmqClientUtils {

    private static final Logger log = LogManager.getLogger();

    /**
     * 发送消息
     *
     * @param host    ip地址
     * @param port    端口
     * @param message 消息
     * @return String 结果
     * @throws Exception 异常信息
     */
    public static String sendMsg(String host, String port, String message) {
        ZMQ.Context context = ZMQ.context(1);
        ZMQ.Socket socket = context.socket(SocketType.REQ);
        socket.setSndHWM(20000);
        socket.setRcvHWM(20000);
        socket.setSendTimeOut(5 * 1000);
        socket.setReceiveTimeOut(5 * 1000);
        socket.connect("tcp://".concat(host).concat(":").concat(port));
        socket.send(message.getBytes(StandardCharsets.UTF_8));
        byte[] response = socket.recv();
        String result = new String(response);
        log.info("接收zmq服务端响应:{}", result);
        socket.close();
        return result;
    }

    public static JsonMsgRequest getJsonFlowDataRequest(JsonMsgRequestType jsonMsgRequestType, String softVer, Object msg) {
        JsonMsgRequest request = new JsonMsgRequest();
        request.setType(jsonMsgRequestType.getType());
        request.setOperate(JsonMsgOperType.QUERYTOTAL.getOperType());
        request.setSequence(0);
        request.setMessage(msg);
        request.setVersion(softVer);
        request.setSize(1);
        request.setSource("HH-TPDC");

        return request;
    }
}
